package logic

import (
	"context"
	"fmt"
	"sendsms/models/cathe"
	"sendsms/models/mysql"

	"sendsms/sendsmsrpc/internal/svc"
	"sendsms/sendsmsrpc/sendsmsrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *sendsmsrpc.RegisterRequest) (*sendsmsrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&findUser)
	if findUser.ID != 0 {
		return nil, fmt.Errorf("当前账号已存在，请前去登录")
	}
	sms := cathe.Rdb.Get(l.ctx, "sendSms"+in.Mobile)
	if sms.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码输入错误，请重新输入")
	}
	if findUser.ID == 0 {

		user := mysql.User{
			Mobile: in.Mobile,
		}
		mysql.DB.Debug().Create(&user)
	}

	return &sendsmsrpc.RegisterResponse{
		UserId: int64(findUser.ID),
	}, nil
}
